package com.chen.controller;

import com.alibaba.fastjson.JSON;
import com.chen.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class UserController {
    @RequestMapping("/json1")
    public String getJson() throws JsonProcessingException {
//        jackson对象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("小明", 34, "男");
        String str = mapper.writeValueAsString(user);
        return str;
    }

    @RequestMapping("json2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper=new ObjectMapper();
        List<User> userList=new ArrayList<User>();
        User user1=new User("大卫",14,"男");
        User user2=new User("大卫2",14,"男");
        User user3=new User("大卫3",14,"男");
        User user4=new User("大卫4",14,"男");
        User user5=new User("大卫5",14,"男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        String str = mapper.writeValueAsString(userList);
        return str;
    }

    @RequestMapping("/json3")
    public String json4(){
        List<User> userList=new ArrayList<User>();
        User user1=new User("大卫",14,"男");
        User user2=new User("大卫2",14,"男");
        User user3=new User("大卫3",14,"男");
        User user4=new User("大卫4",14,"男");
        User user5=new User("大卫5",14,"男");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        String string = JSON.toJSONString(userList);
        return string;
    }

    @RequestMapping("/json4")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper=new ObjectMapper();
//    不使用时间戳的方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);

//        自定义日期格式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(sdf);
        Date date=new Date();
//        String strd= sdf.format(date);
//        ObjectMapper 将时间解析为时间戳
        String str = mapper.writeValueAsString(date);
        return str;
    }

}
